#ifndef     __DRAW_TASK_H
#define     __DRAW_TASK_H

#include "../rtos/thread.h"
#include "../rtos/message_queue.h"
#include "../rtos/event_flags.h"

namespace task {

class DrawTask : public rtos::Thread<DrawTask, 1024, osPriorityHigh1> {

public:
    enum class State : uint8_t {
        WORK = 0,
        TIMEOUT = 1,
        STOP = 2,
        IDLE = 3,
    };
    constexpr static uint32_t FLAG_STOP = 0x01;

    void init_start() {
        m_mq.init();
        m_flags.init();
        this->start();
    }

    void run();

    void stop() {
        m_flags.clr_flags(FLAG_STOP);
        m_mq.post(State::STOP);
        m_flags.wait_any_flags(FLAG_STOP);
    }

    void idle() {
        m_mq.post(State::IDLE);
    }

    inline uint8_t state() {
        return static_cast<uint8_t>(m_state);
    }

private:
    void do_idle();
    void do_stop();
    void do_work();
    void do_timeout();

    bool wait(uint32_t timeout = osWaitForever) {
        return osOK == m_mq.poll(m_state, timeout);
    }

    rtos::MessageQueue<State, 2> m_mq;
    State m_state = State::IDLE;
    rtos::EventFlags m_flags;
};

extern DrawTask drawTask;

}


#endif
